package top.gbyun.engine.processor;

import akka.actor.ActorContext;
import top.gbyun.core.ActorSystemContext;
import top.gbyun.core.api.BasicNode;
import top.gbyun.core.api.NodeContext;
import top.gbyun.core.entity.FlowInfo;
import top.gbyun.core.entity.NodeInfo;
import top.gbyun.core.msg.NodeMsg;
import top.gbyun.core.node.DefaultNodeContext;
import top.gbyun.core.enmus.ComponentLifecycleState;


/**
 * @author gengbin
 * @date 2024-12-26-10:33
 */
public class NodeActorMsgProcessor extends ComponentMsgProcessor {
    private FlowInfo flowInfo;

    private NodeInfo nodeInfo;

    private BasicNode node;

    private NodeContext ndoeCtx;



    public NodeActorMsgProcessor(ActorSystemContext systemContext, FlowInfo flowInfo, NodeInfo nodeInfo,ActorContext ctx) {
        super(systemContext, flowInfo.getId());
        this.flowInfo = flowInfo;
        this.nodeInfo = nodeInfo;
        this.ndoeCtx = new DefaultNodeContext(systemContext, flowInfo,nodeInfo, ctx);
    }

    @Override
    public void start(ActorContext context) throws Exception {
        if (nodeInfo != null) {
            Class<?> executorClazz = Class.forName(nodeInfo.getType());
            node = (BasicNode) (executorClazz.newInstance());
            node.onCreate(ndoeCtx, nodeInfo.getConfig());
        }
        if (node != null) {
            state = ComponentLifecycleState.ACTIVE;
        }
    }

    @Override
    public void stop(ActorContext context) throws Exception {
        if (node != null) {
            node.onDestroy();
            state = ComponentLifecycleState.SUSPENDED;
        }
    }

    @Override
    public void onCreated(ActorContext context) throws Exception {
        start(context);
    }

    @Override
    public void onUpdate(ActorContext context) throws Exception {

    }

    @Override
    public void onActivate(ActorContext context) throws Exception {
        start(context);
    }

    @Override
    public void onSuspend(ActorContext context) throws Exception {
        stop(context);
    }

    @Override
    public void onStop(ActorContext context) throws Exception {
        stop(context);
    }


    public void onFlowToNodeMsg(NodeMsg msg) throws Exception {
        try {
            node.onMessage(ndoeCtx, msg);
        } catch (Exception e) {
           e.printStackTrace();
        }

    }
}
